/*
Section: 4.2
Content: Tables 6,7,10
Paper: "Immigrants Return Intentions and Labor Market Behavior when the Home Country is Unsafe"
Journal: Journal of Labor Economics
Authors: Jacopo Bassetto, Teresa Freitas-Monteiro
*/

********************************************************************************
**# LOAD ANALYSIS DATASET
********************************************************************************
	
use "$final/finaldata_ieb_main_light.dta", replace
	
********************************************************************************
**# Table 6				
********************************************************************************
cap clonevar ln_firmsize_lb = ln_firmsize
cap egen miss =  rowmiss(ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb)

eststo clear
local i=1
foreach out in  unemp_1m unemp_3m  {
foreach control in control control_ext {

global control = "i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp"
global control_ext = "i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb"

qui eststo mod`i': reghdfe `out' treatment_terror_m3y_p90 ${`control'} if  k_treatment_terror_m3y_p90_st==1 & register_unemp==1 & miss == 0, absorb(i.ieb_nat_id#i.year2 i.year2#i.month i.state)  vce(cluster clusterterror_m3y_p90)
sum	 `out' if k_treatment_terror_m3y_p90_st==1 & register_unemp==1 & treatment_terror_m3y_p90 == 0

estadd scalar ymean = r(mean)
estadd local `control' "Yes"
estadd local yearorigin "Yes"
estadd local yearmonth "Yes"
estadd local state "Yes"

local i=`i'+1

	}
	}
	
	
**# TABLE
esttab mod* using "$table/table6_final.tex", star(* 0.10 ** 0.05 *** 0.01) se replace b(3) drop(*edu_max age frau *ysm_atunemp ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb _cons) nocons  nogaps nonotes noob nomtitle ///
mgroups("Emp. within 1m" "Emp. within 3m", pattern(1 0 1 0)   prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
varlabel(treatment_terror_m3y_p90 "Post-Terror") scalars( "nobs Observations" "ymean Mean intention to stay"  "yearorigin Origin country x Year FE" "yearmonth Month FE x Year FE"  "state State of Residency FE" "control Indiv. Controls" "control_ext Extended Controls") sfmt(%9.0fc %9.3f %1s %1s %1s %1s %1s)

		
	
********************************************************************************
**# Table 7		
********************************************************************************

* Firm size before unemployment
cap clonevar ln_firmsize_lb = ln_firmsize

* Non-missings in all job and firm characterisitcs 
cap drop alloutcomes_job alloutcomes_firm
g alloutcomes_job=1 if  ln_wage_any_fa!=. & full_time_fa!=. & ieb_beruf_kons_num_fa!=. 
g alloutcomes_firm=1 if ln_firmsize_fa != . & share_for_fa_ab_med !=. & qualif_hq_fa_ab_med !=. & abovemedian_AKM_fa !=.


***** Panel A: Job characteristics	***** 

	 eststo clear
local i=1
foreach out in  ln_wage_any_fa full_time_fa diff_beruf_kons_num diff_indust_kons_num {
qui eststo mod`i':  reghdfe `out' treatment_terror_m3y_p90 i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp ln_wage_any_lb ln_firmsize_lb  full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb  if  unemp_3m==1 & register_unemp==1 & k_treatment_terror_m3y_p90_st==1 & alloutcomes_job == 1, absorb(i.ieb_nat_id#i.year2 i.month#i.year2 i.state ) vce(cluster clusterterror_m3y_p90)
estadd scalar ymean = r(mean)
	}

esttab mod* using "$table/table7_jobfirmchar_final.tex", star(* 0.10 ** 0.05 *** 0.01) se replace b(3) drop(*edu_max age frau *ysm_atunemp ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb _cons) nocons nogaps nonotes noobs nomtitle ///
posthead("\\ \multicolumn{4}{l}{\textbf{Panel A: Job characteristics (Emp. within 3 months)}}" \\\\[-1ex]) ///
varlabel(treatment_terror_m3y_p90 "Post-Terror") ///
mtitles("\shortstack{Ln hourly\\wage}" "\shortstack{Full-time\\employ.}" "\shortstack{Change\\occup.}" "\shortstack{Change\\industry}") ///
scalars("ymean Mean outcome") sfmt(%9.3f) ///
fragment prehead(" \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{5}{c}} \hline\hline")



***** Panel B: Firm characteristics	***** 
eststo clear
local i=1

 foreach out in ln_firmsize_fa share_for_fa_ab_med qualif_hq_fa_ab_med abovemedian_AKM_fa {
 
 qui eststo mod`i': reghdfe `out' treatment_terror_m3y_p90 i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp ln_firmsize_lb share_for_lb_ab_med qualif_hq_lb_ab_me abovemedian_AKM_lb if unemp_3m==1 & register_unemp==1  & k_treatment_terror_m3y_p90_st==1 & AKM_lb != . & AKM_fa !=. & ln_firmsize_fa !=. & ln_firmsize_lb !=., absorb(i.ieb_nat_id#i.year2  i.month#i.year2 i.state ) vce(cluster clusterterror_m3y_p90)
 
sum	 `out' if k_treatment_terror_m3y_p90_st==1 & register_unemp==1 & treatment_terror_m3y_p90 == 0
estadd scalar ymean = r(mean)
estadd local yearorigin "Yes"
estadd local yearmonth "Yes"
estadd local state "Yes"
estadd local control "Yes"
estadd local control_ext "Yes"


local i=`i'+1
   }

esttab mod* using "$table/table7_jobfirmchar_final.tex", star(* 0.10 ** 0.05 *** 0.01) se append b(3) drop(*edu_max age frau *ysm_atunemp ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb _cons) nocons nogaps nonotes noobs nomtitle ///
posthead("\\ \multicolumn{4}{l}{\textbf{Panel B: Firm characteristics (Emp. within 3 months)}}" \\\\[-1ex]) ///
varlabel(treatment_terror_m3y_p90 "Post-Terror") ///
mtitles("\shortstack{Ln firm\\size}" "\shortstack{Share Germans\\above med}" "\shortstack{Share HS\\above med}" "\shortstack{AKM\\above med}") ///
scalars("nobs Observations" "ymean Mean outcome" "yearorigin Origin country x Year FE" "yearmonth Month FE x Year FE" "state State of Residency FE" "control Individual Controls" "control_ext Extended Controls") ///
sfmt(%9.0fc %9.3f %1s %1s %1s %1s %1s) ///
fragment postfoot("\hline\hline \\ \end{tabular}")

	
	
	
********************************************************************************
**# Table 10		
********************************************************************************

**# DATA MANAGEMENT

	* FROM IEB DATASET FIX COUNTRY CODES ASSIGNED TO THE SAME COUNTRY 
	use "$dataieb/finaldata_ieb_main_light.dta", replace
	gen ieb = 1
	
	* Germany
	replace ieb_nat_id = 0 if ieb_nat_id == 79999
	
	* Hawaii
	replace ieb_nat_id = 368 if ieb_nat_id == 1649999
	
	* Cyprus
	replace ieb_nat_id = 181 if ieb_nat_id == 481
	
	* Hong Kong
	replace ieb_nat_id = 411 if ieb_nat_id == 495
	
	* Sudan
	replace ieb_nat_id = 276 if ieb_nat_id == 277
	replace ieb_nat_id = 276 if ieb_nat_id == 278
	
	* Congo
	replace ieb_nat_id = 443 if ieb_nat_id == 421
	
	* Yemen
	replace ieb_nat_id = 133 if ieb_nat_id == 170
 
	
* LOAD COUNTRY CODES AND FIX COUNTRY CODES FOR SOEP AND IEB SO THAT THEY ARE UNIQUE AT THE IEB AND SOEP ORIGIN

preserve 
import excel using "$codes/country_codes_soep_ieb.xlsx", sheet("correspondence") firstrow clear

	* 128 Malaysia 
		replace soep_corigin_id = 104 if soep_corigin_id == 128
		* 155 Turkmenistan
		replace soep_corigin_id = 91 if soep_corigin_id == 155
		* 7 Germany
		replace soep_corigin_id = 1 if soep_corigin_id == 7
		* USA
		replace soep_corigin_id = 18 if soep_corigin_id == 164
		 *168 Montenegro  
		replace soep_corigin_id = 106 if soep_corigin_id == 168
		*145 Mongolia  129 Samoa missin
		
		* Germany
		replace ieb_nat_id = 0 if ieb_nat_id == 79999
		
		* Hawaii
		replace ieb_nat_id = 368 if ieb_nat_id == 1649999
		
		* Cyprus
		replace ieb_nat_id = 181 if ieb_nat_id == 481
		
		* Hong Kong
		replace ieb_nat_id = 411 if ieb_nat_id == 495
		
		* Sudan
		replace ieb_nat_id = 276 if ieb_nat_id == 277
		replace ieb_nat_id = 276 if ieb_nat_id == 278
		
		* Congo
		replace ieb_nat_id = 443 if ieb_nat_id == 421
		
		* Yemen
		replace ieb_nat_id = 133 if ieb_nat_id == 170
						
	duplicates drop ieb_nat_id, force
	duplicates drop soep_corigin_id, force
	
	tempfile soep_code
	save `soep_code'
	
restore
	
merge m:1 ieb_nat_id using `soep_code', gen(merge_soep_id) keep(3)
		
* Append SOEP
preserve 

	global datasoep "$data/soepdata"

	use "$datasoep/main_final/finaldata_terrorsoep_light_final.dta", clear

	gen soep = 1 

	merge m:1 soep_corigin_id using `soep_code', gen(merge_ieb_id) keep(3)

	tempfile soep
	save `soep'

restore
	
append using `soep'
	

**# GENERATE COMMON VARIABLES
	* YEAR
	gen year_c = syear if soep == 1
	replace year_c = year2 if ieb == 1

	* STATE
	gen bula_c = bula if soep == 1
	replace bula_c = woao_land if ieb == 1

	* SEX 
	gen sex_c = sex if soep == 1
	replace sex_c = frau if ieb == 1

	* YSM 
	gen ysm_c = ysm if soep == 1
	replace ysm_c = ysm_atunemp if ieb == 1

	* Treat
	gen terror_c = postterror_m3y_p90 if soep == 1
	replace terror_c = treatment_terror_m3y_p90 if ieb == 1
	

****# Panel A: Outcome Equation (reduced form and 2SLS)****
* Reduced form results (Column 1)
global control_ext = "i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb"

eststo clear
eststo reduced: reghdfe unemp_3m treatment_terror_m3y_p90 $control_ext if k_treatment_terror_m3y_p90_st==1 & register_unemp==1 & miss == 0, absorb(i.ieb_nat_id#i.year2 i.year2#i.month i.state) vce(cluster clusterterror_m3y_p90)

* Add fixed effects locals for reduced form
estadd local yearorigin "Yes": reduced
estadd local yearmonth "Yes": reduced  
estadd local state "Yes": reduced
estadd local control "Yes": reduced

**# Second stage (Column 2) 
** First stage for IV
global select_reg_M "!inlist(soep_corigin_id,.,1) & inrange(distanceterror_m3y_p90,-3,3) & distanceterror_m3y_p90!= 0"
global controls "i.soep_corigin_id#i.year_c i.bula_c i.year_c#i.month"
reghdfe remain_ger_per terror_c i.sex_c c.age c.ysm_c##c.ysm_c if $select_reg_M & sample_terror_m3y ==1, vce(cluster clusterterror_m3y_p90) absorb($controls)

predict remain_ger_per_hat, xb
mat FS_mP = [e(rmse), 0 \ 0, 0]
global NFS_mP = "6604"

** Second stage
cap clonevar ln_firmsize_lb = ln_firmsize
cap egen miss = rowmiss(ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb)

eststo iv: reghdfe unemp_3m remain_ger_per_hat i.sex_c c.age c.ysm_c##c.ysm_c if k_treatment_terror_m3y_p90_st==1 & register_unemp==1 & miss == 0, absorb(i.soep_corigin_id#i.year_c i.year_c#i.month i.bula_c) vce(cluster clusterterror_m3y_p90)

**# CORRECTION FACTOR c (following Inoue and Solon 2010)
mat b = e(b)
mat R = J(colsof(b), colsof(b), 0)
mat R[1,1] = FS_mP[1,1]
mat c = 1 + e(N)/${NFS_mP} * 1/e(rmse) * b * R * b'
scalar correction_factor = c[1,1]

**# Apply correction by replacing the variance matrix
mat V_corrected = e(V) * correction_factor
ereturn repost V = V_corrected

* Add fixed effects locals for IV
estadd local yearorigin "Yes": iv
estadd local yearmonth "Yes": iv
estadd local state "Yes": iv  
estadd local control "Yes": iv

**# Panel B: First-stage results
eststo firststage: reghdfe remain_ger_per terror_c i.sex_c c.age c.ysm_c##c.ysm_c if $select_reg_M & sample_terror_m3y ==1, vce(cluster clusterterror_m3y_p90) absorb($controls)

* Add F-statistic and locals for first stage
test terror_c
estadd scalar fstat = r(F)
estadd local yearorigin "Yes": firststage
estadd local yearmonth "Yes": firststage
estadd local state "Yes": firststage
estadd local control "Yes": firststage

**# Create the combined table
esttab reduced iv using "$table/table10_2SLS.tex", ///
    mgroups("Panel A: Outcome Equation (dependent variable: re-employment within 3 months)" "Reduced form" "Two Sample-2SLS", pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
    mtitles("(1)" "(2)") varlabel(treatment_terror_m3y_p90 "Post-Terror" remain_ger_per_hat "Intention to stay in Germany") ///
    keep(treatment_terror_m3y_p90 remain_ger_per_hat) ///
    star(* 0.10 ** 0.05 *** 0.01) se b(3) nonotes noobs nogaps fragment replace prehead(" \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{5}{c}} \hline\hline")


esttab firststage using "$table/table10_2SLS.tex", ///
    mgroups("Panel B: First-stage Equation (dependent variable: intention to stay in Germany)", pattern(1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
    mtitles("") varlabel(terror_c "Post-Terror") ///
    keep(terror_c) star(* 0.10 ** 0.05 *** 0.01) se b(3) ///
    scalars("nobs Observations" "fstat F-statistic" "yearorigin Origin country FE x Year FE" "yearmonth Year FE x Month FE" "state State FE" "control Individual Controls") ///
    sfmt(%9.0fc %9.2f %1s %1s %1s %1s) nonotes nogaps fragment append  postfoot("\hline\hline \\ \end{tabular}")
